/**
 * 时间相关帮助函数
 *
 * @author 俞杰
 * @email 158392613@qq.com
 */
import { addZero } from './numberHelper'

/**
 * 时间格式化函数
 *
 * @param time 标准时间字符串或者时间戳
 * @param rule
 * @returns
 */
export const formatTime = (
  time: string | number,
  rule = 'yyyy-MM-dd hh:mm:ss'
) => {
  let timeObject = new Date(time)
  if (timeObject.toString() === 'Invalid Date') {
    timeObject = new Date(Number(time))
  }
  let fmt = rule
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, timeObject.getFullYear() + '')
  }
  const regList = {
    'M+': timeObject.getMonth() + 1 + '',
    'd+': timeObject.getDate() + '',
    'h+': timeObject.getHours() + '',
    'm+': timeObject.getMinutes() + '',
    's+': timeObject.getSeconds() + '',
  }
  for (const reg in regList) {
    const timeValue = regList[reg as keyof typeof regList]
    const regObj = new RegExp(`(${reg})`)
    if (regObj.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, addZero(timeValue, 2))
    }
  }
  return fmt
}
